<template>
  <div class="page">
    <!-- 页面头部 -->
    <el-card class="page-header">
      <el-page-header @back="() => {}" content="维修人员管理">
        <template #content>
          <div class="page-title">
            <h2>🔧 维修人员管理</h2>
            <p class="page-subtitle">管理维修人员信息，包括技能等级、工作状态等</p>
          </div>
        </template>
        <template #extra>
          <div class="page-actions">
            <el-button type="success" @click="showAddModal = true">
              <el-icon><Plus /></el-icon>
              新增维修员
            </el-button>
            <el-button @click="refreshMaintainers">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </template>
      </el-page-header>
    </el-card>


    <!-- 内容卡片 -->
    <el-card class="content-card">
      <!-- 搜索和筛选 -->
      <template #header>
        <el-row :gutter="16" align="middle">
          <el-col :span="8">
            <el-input
              v-model="searchQuery"
              placeholder="搜索姓名、电话、技能类型..."
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="5">
            <el-select v-model="statusFilter" placeholder="全部状态" clearable >
              <el-option label="正常" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-select v-model="levelFilter" placeholder="全部类型" clearable>
              <el-option label="水电维修" :value="0" />
              <el-option label="家具维修" :value="1" />
              <el-option label="网络维修" :value="2" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select v-model="skillFilter" placeholder="全部工作状态" clearable>
              <el-option label="工作中" :value="1" />
              <el-option label="休息" :value="0" />
            </el-select>
          </el-col>
        </el-row>
      </template>

      <!-- 维修人员列表 -->
      <el-table :data="filteredMaintainers" stripe>
        <el-table-column label="维修员信息" min-width="200">
          <template #default="{ row }">
            <div class="maintainer-info">
              <el-avatar :size="40" :src="row.avatar">
                {{ row.name.charAt(0) }}
              </el-avatar>
              <div class="info">
                <div class="name">{{ row.name }}</div>
                <div class="phone">{{ row.phone }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="技能类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="工作状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getWorkStatusTagType(row.workStatus)">
              {{ getWorkStatusText(row.workStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        
        
        <el-table-column label="入职时间" width="120">
          <template #default="{ row }">
            <span class="join-date">{{ formatDate(row.createTime) }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button size="small" type="warning" @click="editMaintainer(row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button size="small" type="danger" @click="deleteMaintainer(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑维修员对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="showAddModal ? '新增维修员' : '编辑维修员'"
      width="600px"
      @close="closeModal"
    >
      <el-form :model="maintainerForm" label-width="80px">
        <el-form-item label="姓名" required>
          <el-input 
            v-model="maintainerForm.name"
            placeholder="请输入姓名"
          />
        </el-form-item>
        
        <el-form-item label="手机号" required>
          <el-input 
            v-model="maintainerForm.phone"
            placeholder="请输入手机号"
          />
        </el-form-item>
        
        <el-form-item label="技能类型" required>
          <el-select v-model="maintainerForm.type" placeholder="请选择技能类型">
            <el-option label="水电维修" :value="0" />
            <el-option label="家具维修" :value="1" />
            <el-option label="网络维修" :value="2" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态" required>
          <el-select v-model="maintainerForm.status" placeholder="请选择状态">
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="工作状态" required>
          <el-select v-model="maintainerForm.workStatus" placeholder="请选择工作状态">
            <el-option label="工作中" :value="1" />
            <el-option label="休息" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="saveMaintainer">
          {{ showAddModal ? '新增' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryMaintainerAPI, addMaintainerAPI, updateMaintainerAPI, deleteMaintainerAPI } from '@/apis/maintainerAPI'

// 响应式数据
const searchQuery = ref('')
const statusFilter = ref('')
const levelFilter = ref('')
const skillFilter = ref('')
const showAddModal = ref(false)
const showEditModal = ref(false)
const editingMaintainer = ref(null)

const dialogVisible = computed({
  get: () => showAddModal.value || showEditModal.value,
  set: (val) => {
    if (!val) {
      showAddModal.value = false
      showEditModal.value = false
    }
  }
})

// 维修员表单
const maintainerForm = ref({
  name: '',
  phone: '',
  type: 0,
  status: 1,
  workStatus: 1
})

// 维修员数据
const maintainers = ref([])

// 计算属性
const filteredMaintainers = computed(() => {
  let filtered = maintainers.value

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(maintainer => 
      maintainer.name.toLowerCase().includes(query) ||
      maintainer.phone.includes(query) ||
      getTypeText(maintainer.type).toLowerCase().includes(query)
    )
  }

  // 状态过滤
  if (statusFilter.value !== '' && statusFilter.value!==null&& statusFilter.value!==undefined) {
    filtered = filtered.filter(maintainer => maintainer.status === statusFilter.value)
  }

  // 类型过滤
  if (levelFilter.value !== '' && levelFilter.value!==null&& levelFilter.value!==undefined) {
    filtered = filtered.filter(maintainer => maintainer.type === levelFilter.value)
  }

  // 工作状态过滤
  if (skillFilter.value !== '' && skillFilter.value!==null&& skillFilter.value!==undefined) {
    filtered = filtered.filter(maintainer => maintainer.workStatus === skillFilter.value)
  }

  return filtered
})



// 方法
const getTypeText = (type) => {
  const typeMap = {
    0: '水电维修',
    1: '家具维修',
    2: '网络维修'
  }
  return typeMap[type]
}


const getWorkStatusText = (workStatus) => {
  return workStatus === 1 ? '工作中' : '休息'
}

const getTypeTagType = (type) => {
  const typeMap = {
    0: 'primary',
    1: 'warning',
    2: 'success'
  }
  return typeMap[type]
}

const getWorkStatusTagType = (workStatus) => {
  return workStatus === 1 ? 'danger' : 'warning'
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 加载维修员数据
const loadMaintainers = async () => {
  try {
    const response = await queryMaintainerAPI()
    if (response.code === 0) {
      maintainers.value = response.data
    } else {
      ElMessage.error(response.message || '加载数据失败')
    }
  } catch (error) {
    console.error('加载维修员数据失败:', error)
    ElMessage.error('加载数据失败，请重试')
  }
}

const refreshMaintainers = () => {
  loadMaintainers()
}


const editMaintainer = (maintainer) => {
  editingMaintainer.value = maintainer
  maintainerForm.value = { ...maintainer }
  showEditModal.value = true
}

const deleteMaintainer = async (maintainer) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除维修员 "${maintainer.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await deleteMaintainerAPI(maintainer.id)
    if (response.code === 0) {
      ElMessage.success('删除成功')
      await loadMaintainers() // 重新加载数据
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除维修员失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}

const saveMaintainer = async () => {
  try {
    // 表单验证
    if (!maintainerForm.value.name.trim()) {
      ElMessage.warning('请输入姓名')
      return
    }
    if (!maintainerForm.value.phone.trim()) {
      ElMessage.warning('请输入手机号')
      return
    }
    
    let response
    if (showAddModal.value) {
      // 添加新维修员
      response = await addMaintainerAPI(maintainerForm.value)
      if (response.code === 0) {
        ElMessage.success('新增成功')
        await loadMaintainers() // 重新加载数据
      } else {
        ElMessage.error(response.message || '新增失败')
        return
      }
    } else {
      // 编辑维修员 - 只传递必要的字段，不包含创建时间和修改时间
      const updateData = {
        id: editingMaintainer.value.id,
        name: maintainerForm.value.name,
        phone: maintainerForm.value.phone,
        type: maintainerForm.value.type,
        status: maintainerForm.value.status,
        workStatus: maintainerForm.value.workStatus
      }
      response = await updateMaintainerAPI(updateData)
      if (response.code === 0) {
        ElMessage.success('更新成功')
        await loadMaintainers() // 重新加载数据
      } else {
        ElMessage.error(response.message || '更新失败')
        return
      }
    }
    closeModal()
  } catch (error) {
    console.error('保存维修员失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  editingMaintainer.value = null
  maintainerForm.value = {
    name: '',
    phone: '',
    type: 0,
    status: 1,
    workStatus: 1
  }
}

onMounted(() => {
  loadMaintainers()
})
</script>

<style scoped>
.page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-title h2 {
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 4px;
}

.page-subtitle {
  color: #7f8c8d;
  font-size: 14px;
  margin: 0;
}

.content-card {
  margin-bottom: 20px;
}

.maintainer-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.name {
  font-weight: 500;
  color: #2c3e50;
}


.phone {
  font-size: 12px;
  color: #7f8c8d;
}



.join-date {
  color: #7f8c8d;
  font-size: 14px;
}
</style>
